package com.xyzk.diagnose.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.xyzk.diagnose.R;
import com.xyzk.diagnose.activity.adapter.DiagnoseAdapter;
import com.xyzk.diagnose.activity.adapter.SettingAdapter;
import com.xyzk.diagnose.activity.bluetooth.BluetoothService;
import com.xyzk.diagnose.entity.Cartype;
import com.xyzk.diagnose.tools.Common;
import com.xyzk.diagnose.tools.Commonfunc;
import com.xyzk.diagnose.tools.FileReader;
import com.xyzk.diagnose.view.CToast;
import com.xyzk.diagnose.view.dialog.ProgressDialog;
import com.xyzk.diagnose.view.dialog.ShowDialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Service;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("HandlerLeak")
public class DiagnoseActivity extends Activity {
	private WakeLock wakeLock;
	private TextView tvTip;
	private Button btnReDiag;
	private ListView lvModule,lvShowData;
	private SettingAdapter moduleAdapter;//模块列表
	private DiagnoseAdapter dataAdapter;//检测显示数据
	private List<ArrayList<Map<String, String>>> allDatas = new ArrayList<ArrayList<Map<String, String>>>();
	private ArrayList<Map<String, String>> showDatas = new ArrayList<Map<String,String>>();
	private DiagnoseThread mThread;
	private ProgressDialog progressdialog;
	private ShowDialog mDialog;
	private int modulePos = -1;//检测第几个模块
	private int auto;
	private int pos = 0;  //模块下标
	private String module;
	private BluetoothService mBlueService = BluetoothService.getInstance();
	private Cartype cartype = Cartype.getInstance();
	private boolean exit = true;
	private boolean reDiagnose;//重新检测

	private Handler mHandler = new Handler(){
		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case Common.BLUE_RECEIVE_CONNECT:
					progressdialog.dismiss();
					if(mBlueService.isConnected()){
						CToast.show("连接成功!");
						startThread();
					}else{
						CToast.show("连接失败,请退出重新连接!");
					}
					break;
				case Common.BLUE_AUTO_CONNECT_BLUETOOTH:
					connectBluetooth();
					break;
				case Common.TEXTVIEW_SHOW_TIP: //显示提示信息
					String text = (String)msg.obj;
					tvTip.setText(text);
					if(text.equals(getString(R.string.func_show_saveresult)))
					{
						exit = true;
						lvModule.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
						ArrayList<Map<String, String>> data = new ArrayList<Map<String,String>>();
						data.addAll(showDatas);
						allDatas.add(data);//添加最后一个模块的数据
						mThread.setAllShowDatas(allDatas);
						if(reDiagnose){
							reStartDiagnose();
						}
					}
					break;
				case Common.FLASH_DATA_LIST://显示检测数据列表更新
					HashMap<String, String> map = (HashMap<String, String>) msg.obj;
					if(Common.NG.equals(map.get(Common.RESULT))){
						moduleAdapter.addErrorId(modulePos);
					}
					showDatas.add(map);
					dataAdapter.notifyDataSetChanged();
					break;
				case Common.FLASH_MODULE_LIST://更新模块列表，检测列表
					modulePos ++;
					if(modulePos > 9){//界面随检测模块滚动
						lvModule.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
					}
					flashDiagnoseList();
					break;
				case Common.DIALOG_SHOW_TEXT:
					mDialog = new ShowDialog(DiagnoseActivity.this);
					mDialog.setTime(msg.arg1);
					mDialog.setText((String)msg.obj);//直接显示文本
					break;
				case Common.DIALOG_SHOW_YES_NO: //显示提示信息对话框
					mDialog = new ShowDialog(DiagnoseActivity.this);
					mDialog.setText((String)msg.obj);
					mDialog.showCancelButton();
					break;
				case Common.DIALOG_WAIT_AUTO_CLOSE:  //显示文本并自动关闭
					mDialog = new ShowDialog(DiagnoseActivity.this);
					mDialog.setTime(msg.arg1);
					mDialog.setText((String)msg.obj);
					mDialog.setAutoClose();
					break;
				case Common.MSG_Dialog_WaitTime:
					if(mDialog != null)
					{
						mDialog.dismiss();
						mDialog = null;
					}
					mDialog = new ShowDialog(DiagnoseActivity.this);
					mDialog.setTime(msg.arg1);
					if(msg.arg2 == 1) //ON
						mDialog.setText(R.string.msg_show_keyon);
					else if(msg.arg2 == 2) //OFF
						mDialog.setText(R.string.msg_show_keyoff);
					else if(msg.arg2 == 3) //直接显示文本
						mDialog.setText((String)msg.obj);
					else if(msg.arg2 == 4) //OFF
						mDialog.setText(R.string.msg_show_context6);
					else if(msg.arg2 == 5) //OFF
						mDialog.setText(R.string.msg_show_context7);
					else if(msg.arg2 == 6) //WAIT
						mDialog.setText(R.string.msg_show_context10);
					else if(msg.arg2 == 7) //START
						mDialog.setText(R.string.msg_show_keystart);
					else
						mDialog.setText((String) msg.obj);
					mDialog.show();
					//Common.wait = false;
					break;
			}
		};
	};

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_diagnose);
		//保持界面常亮
		PowerManager pm = (PowerManager)getSystemService(Service.POWER_SERVICE);
		wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Lock");
		wakeLock.setReferenceCounted(false);

		initViews();

		if(auto > 0){
			startThread();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		wakeLock.acquire();


	}

	@Override
	protected void onPause() {
		super.onPause();
		wakeLock.release();
	}


	/**
	 * 初始化控件
	 */
	private void initViews()
	{	if(Common.stationPos == 3 && (cartype.car.indexOf("62") > 0 || cartype.car.indexOf("63") > 0)) //公共刷写
		{
			FileReader.readStep(cartype.flashDirectory + "step_" + Common.stationPos + ".ini");
		}
		else
			FileReader.readStep(cartype.carDirectory + "step_" + Common.stationPos + ".ini");

		auto = cartype.getMap("AUTO");

		TextView tvTitle = (TextView)findViewById(R.id.tv_diagnose_title);
		tvTitle.setText(cartype.getStationsList().get(Common.stationPos));
		TextView tvCartype = (TextView)findViewById(R.id.tv_diagnose_cartype_info);
		tvCartype.setText(new String(cartype.vin) + "\n" + cartype.name);

		tvTip = (TextView)findViewById(R.id.tv_diagnose_tip);
		btnReDiag = (Button)findViewById(R.id.btn_diagnose_rediagnose);

		if(auto == 0){//返修的时候不需要重新检测按键
			btnReDiag.setVisibility(View.INVISIBLE);
		}

		lvModule = (ListView) findViewById(R.id.lv_module_list);
		moduleAdapter = new SettingAdapter(cartype.getModuleListFilter(), R.layout.activity_diagnose_module_item);
		lvModule.setAdapter(moduleAdapter);

		lvShowData = (ListView) findViewById(R.id.lv_data_list);
		dataAdapter = new DiagnoseAdapter(showDatas);
		lvShowData.setAdapter(dataAdapter);

		lvModule.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
				pos = position;
				onItemClickModule();
			}
		});

		btnReDiag.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(!exit){//检测中
					reDiagnose = true;
					setExit(true);//先退出
				}else{
					reStartDiagnose();
				}
			}
		});
	}

	/**
	 * 重新检测时，清除刚刚检测的信息
	 */
	private void clearDiagnoseInfo(){
		showDatas.clear();
		allDatas.clear();
		cartype.result = 0;
		dataAdapter.notifyDataSetChanged();
		//重新让左侧列表回到最上面一个模块
		moduleAdapter = new SettingAdapter(cartype.getModuleListFilter(), R.layout.activity_diagnose_module_item);
		lvModule.setAdapter(moduleAdapter);
		lvModule.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
		modulePos = -1;
	}

	/**
	 * item点击事件处理
	 * @param pos item下标
	 */
	private void onItemClickModule(){
		if(!exit){//检测中，不能点击
			CToast.show(R.string.DiagnoseActivity_diagnoseing);
			return;
		}else{
			moduleAdapter.setSelected(pos);
			moduleAdapter.notifyDataSetChanged();
			showDatas.clear();

			if(auto > 0){//自动检测 就是查看检测结果
				if(allDatas.size() > pos){
					showDatas.addAll(allDatas.get(pos));
					dataAdapter.notifyDataSetChanged();
				}
			}else{//返修 点击就是诊断
				dataAdapter.notifyDataSetChanged();
				module = cartype.getModuleListFilter().get(pos);
				cartype.result = 0;
				if(!mBlueService.isConnected()){
					connectBluetooth();
				}else{
					startThread();
				}
			}
		}
	}

	/**
	 * 连接蓝牙
	 */
	private void connectBluetooth(){
		mBlueService.setHandler(mHandler);
		mBlueService.connectDevice(Commonfunc.getSharedPreference(Common.MAC_ADDRESS, "00:00:00:00:00:00"));
		progressdialog = ProgressDialog.createDialog(this, "正在连接蓝牙...");
	}

	/**
	 * 执行AUTO > 0的工位时，更新列表
	 */
	private void flashDiagnoseList(){
		//module列表更新
		moduleAdapter.setSelected(modulePos);
		moduleAdapter.notifyDataSetChanged();
		ArrayList<Map<String, String>> data = new ArrayList<Map<String, String>>();
		if(showDatas.size() != 0){//第一个模块时,前面无数据
			data.addAll(showDatas);
			allDatas.add(data);
			showDatas.clear();
		}
		dataAdapter.notifyDataSetChanged();
	}


	/**
	 * 开始诊断线程
	 */
	private void startThread(){
		mThread = new DiagnoseThread(module, mHandler);
		mThread.start();
		setExit(false);
	}
	/**
	 * 重新检测
	 */
	private void reStartDiagnose(){
		reDiagnose = false;
		clearDiagnoseInfo();
		startThread();
	}

	/**
	 * 退出
	 */
	private void setExit(boolean ex){
		exit = ex;
		if(mThread != null){
			mThread.setExit(ex);
		}
	}

	@Override
	protected void onDestroy() {
		setExit(true);
		super.onDestroy();
	}



	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch(keyCode){
			case KeyEvent.KEYCODE_BACK:
				if(!exit){
					final ShowDialog dialog = new ShowDialog(this);
					dialog.setText(R.string.DiagnoseActivity_dialog_exit);
					dialog.showCancelButton();
					dialog.onClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							if(auto == 0){//返修，就不退出Activity
								setExit(true);
							}else{
								finish();
							}
							dialog.dismiss();
						}
					});
					return true;
				}else{
					finish();
				}
		}
		return super.onKeyDown(keyCode, event);
	}
}